/**
 * 定义路由： Router.[method](path, (request, response) => { })
 *    Router: 路由实例
 *    app.method(path, (request, response) => { })
 */
// 使用 multer 处理文件上传
const multer = require("multer");
const { v4: uuid } = require("uuid");
const path = require("path");
// 配置上传文件的存储位置和文件名
const storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "./public/avatars");
  },
  filename: function (req, file, cb) {
    const ext = path.extname(file.originalname);
    cb(null, uuid() + ext);
  },
});
const upload = multer({ storage });

const { db } = require("../database");

const { validate, validators } = require("../validate");

// 导入加密函数
const { makePassword, checkPassword } = require("../utils");
// jwt
const { sign } = require("./jwt");

const registerRouter = (app) =>
  app
    /**
     * 用户注册
     */
    .post(
      "/register",
      upload.single("avatar"),
      validate(
        validators.username,
        validators.password,
        validators.confirmPassword,
        validators.nickname
      ),
      async (req, res) => {
        const { username, password, nickname } = req.body;
        const exist = await db.findOne(
          "select * from user where username = ?",
          [username]
        );
        if (exist) {
          return res.send({
            success: false,
            errors: { username: ["该用户名已经存在"] },
          });
        }
        // 插入用户信息
        const results = await db.select(
          "insert into user (username, password, nickname, avatar) values (?, ?, ?, ?)",
          [username, makePassword(password), nickname, req.file?.filename]
        );
        // 查询刚刚插入的用户信息
        const user = await db.findOne("select * from user where id = ?", [
          results.insertId,
        ]);
        res.send({
          success: true,
          user,
        });
      }
    )
    /**
     * 用户登录
     */
    .post(
      "/login",
      validate(validators.username, validators.password),
      async (req, res) => {
        const { username, password } = req.body;
        // 根据用户名查询用户信息
        const user = await db.findOne("select * from user where username = ?", [
          username,
        ]);
        // 判断密码是否输入正确
        if (user && checkPassword(password, user.password)) {
          // 在会话（session）中保存用户信息
          req.session.userId = user.id;
          // 签发 token 给客户端代码
          const token = sign({ userId: user.id });
          return res.send({
            success: true,
            user,
            token,
          });
        }
        
        res.send({ success: false, message: "用户名或密码错误！" });
      }
    );

module.exports = { registerRouter };
